<template>
  <el-row :gutter="20" type="flex">
    <el-col :span="15">
      <NewCard title="充值设置">
        <ComTable
          :pagination="{
            total: pageing.total,
            pageNum: pageing.pageNum,
            pageSize: pageing.pageSize,
          }"
          @EventRowClick="RowClickFn"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
          :list="tableList"
          :modes="tableModes"
        >
        </ComTable>
      </NewCard>
    </el-col>
    <el-col :span="9">
      <NewCard :title="title">
        <el-form
          ref="form"
          :rules="rules"
          :model="editForm"
          label-width="140px"
          label-position="left"
        >
          <el-form-item label="充值金额" prop="amount">
            <el-input v-model="editForm.amount" :disabled="editForm.custom"></el-input>
          </el-form-item>
          <el-form-item label="赠送规则" v-if="editForm.custom" class="customBox" v-hasPermi="['base:config:depositSetting']">
            <p>每超出</p>
            <el-form-item prop="limit">
              <el-input v-model.number="editForm.limit"></el-input>
            </el-form-item>
            <p>赠送</p>
            <el-form-item prop="scale">
              <el-input v-model="editForm.scale"></el-input>
            </el-form-item>
            <p>%</p>
          </el-form-item>
          <el-form-item label="获得问金" prop="voucher" v-else>
            <el-input v-model="editForm.voucher"></el-input>
          </el-form-item>
          <el-form-item label="有效期（天）" prop="expiration">
            <el-input v-model="editForm.expiration"></el-input>
          </el-form-item>
          <!-- <el-form-item label="渠道拨比" prop="placeCommission">
            <el-input v-model="editForm.placeCommission"></el-input>
          </el-form-item>
          <el-form-item label="商务经理拨比" prop="cmCommission">
            <el-input v-model="editForm.cmCommission"></el-input>
          </el-form-item>
          <el-form-item label="商务总监拨比" prop="directorCommission">
            <el-input v-model="editForm.directorCommission"></el-input>
          </el-form-item> -->
          <SubBtn>
            <template slot="btn">
              <el-button round @click="remove" v-if="!editForm.custom">删除</el-button>
              <el-button round @click="addinfo" v-if="!editForm.custom">新增</el-button>
              <el-button type="primary" @click="submit" round v-if="!editForm.custom" v-hasPermi="['financial:depositVoucher:edit']">保存</el-button>
              <!-- 自定义金额的保存按钮 -->
              <el-button type="primary" @click="customSubmit" round v-if="editForm.custom" v-hasPermi="['base:config:edit']">保存</el-button>
            </template>
          </SubBtn>
        </el-form>
      </NewCard>
    </el-col>
  </el-row>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import ComTable from "@/wss/components/comTable.vue";
import SubBtn from "@/wss/components/subBtn.vue";
import {
  getdepositVoucherApi,
  editlistInvoisceApi,
  addlistInvoisceApi,
  removelistInvoisceApi,
  getConfigDepositSettingApi,
  editConfigApi,
} from "@/wss/newApi_3-24/base/config.js";

export default {
  name: "Recharge",
  components: { NewCard, ComTable, SubBtn },
  data() {
    // 0-100之间的数，包含小数 
    const scaleRul = new RegExp(/^(\d{1,2}(\.\d{1,2})?|100)$/);
    // 只能输入正整数
    const limitRul = new RegExp(/^\+?[1-9][0-9]*$/);
    return {
      // 分页参数
      pageing: { pageNum: 1, pageSize: 10, total: 0 },
      title: "新增",
      // 表格配置
      tableModes: [
        {
          label: "序号",
          type: "index",
          width: 50,
        },
        {
          label: "充值金额",
          mode: "amount",
        },
        {
          label: "获得问金",
          mode: "voucher",
        },
        {
          label: "问金有效期(天)",
          mode: "expiration",
        },
        // {
        //   label: "渠道拨比(%)",
        //   mode: "placeCommission",
        // },
        // {
        //   label: "商务经理拨比(%)",
        //   mode: "cmCommission",
        // },
        // {
        //   label: "商务总监拨比(%)",
        //   mode: "directorCommission",
        // },
      ],
      rules: {
        amount: [
          {
            required: true,
            message: "请输入充值金额",
            trigger: "blur",
          },
        ],
        voucher: [
          {
            required: true,
            message: "请输入获得问金",
            trigger: "blur",
          },
        ],
        amount: [
          {
            required: true,
            message: "请输入充值金额",
            trigger: "blur",
          },
        ],
        expiration: [
          {
            required: true,
            message: "请输入有效期（天）",
            trigger: "blur",
          },
        ],
        // 每多少元增加赠送比例
        limit:[
          { required: true,message: "增加比例",trigger: "blur", },
          { pattern: limitRul,message: "请输入正整数",trigger: "blur",},
        ],
        // 每多少元增加赠送比例
        scale:[
          { required: true,message: "赠送比例",trigger: "blur",},
          { pattern: scaleRul,message: "0-100之间",trigger: "blur",},
        ],
        // placeCommission: [
        //   {
        //     required: true,
        //     message: "请输入渠道拨比,0-1之间(%)",
        //     trigger: "blur",
        //     validator: this.validatePass,
        //   },
        // ],
        // cmCommission: [
        //   {
        //     required: true,
        //     message: "请输入商务经理拨比,0-1之间(%)",
        //     trigger: "blur",
        //     validator: this.validatePass,
        //   },
        // ],
        // directorCommission: [
        //   {
        //     required: true,
        //     message: "请输入商务总监拨比(%),0-1之间",
        //     trigger: "blur",
        //     validator: this.validatePass,
        //   },
        // ],
      },
      // 表格数据
      tableList: [],

      //当前编辑的表单
      editForm: {},
    };
  },
  async mounted() {
    await this.getdepositVoucherApiFn();
    this.getConfigDepositSetting()//自定义金额
  },
  methods: {
    validatePass(rule, value, callback) {
      if (value == "") return callback(new Error("年龄不能为空"));
      value = Number(value);
      console.log(value);
      if (typeof value == "number") {
        if (value <= 1 && value >= 0) return callback();
      }
      callback(new Error("年龄不能为空"));
    },
    // 获取提现设置数据
    async getdepositVoucherApiFn() {
      let { rows, code, total } = await getdepositVoucherApi(this.pageing);
      if (code == 200) {
        this.pageing.total = total;
        this.tableList = rows;

        // 添加一条自定义金额
        let custom = {
          amount: '自定义金额', //充值金额
          expirationId: '',//问金有效期id
          expiration: '',//问金有效期
          limitId: '',//每多少元增加赠送比例id
          limit: '',//每多少元增加赠送比例
          scaleId: '',//赠送比例Id
          scale: '',//赠送比例
          custom: true, //标识是自定义金额
        }
        this.tableList.push(custom)
      }
    },
    RowClickFn(row) {
      console.log(row, "1111");
      this.title = "编辑";
      let changeRow = JSON.parse(JSON.stringify(row));
      this.editForm = changeRow;
    },
    //保存
    async submit() {
      try {
        await this.$refs.form["validate"]();
        let editForm = this.editForm;
        if (this.editForm.id == null) {
          let { code, msg } = await addlistInvoisceApi(editForm);
          if (code != 200) return;
          this.editForm = {};
          this.getdepositVoucherApiFn();
          this.$message({
            message: msg,
            type: "success",
          });
        } else {
         
          let { code, msg } = await editlistInvoisceApi(editForm);
          if (code != 200) return;
          this.editForm = {};
          this.getdepositVoucherApiFn();
          this.$message({
            message: msg,
            type: "success",
          });
           this.title = "新增";
        }
      } catch (error) {}
    },

    //新增
    async addinfo() {
      let editForm = this.editForm;
      try {
        await this.$refs.form["validate"]();
        let { code, msg } = await addlistInvoisceApi(editForm);
        if (code != 200) return;
        this.editForm = {};
        this.getdepositVoucherApiFn();
        this.$message({
          message: msg,
          type: "success",
        });
      } catch (error) {}
    },

    // 删除
    async remove() {
      console.log(this.editForm.id, "123");
      if (this.editForm.id) {
        let { code, msg } = await removelistInvoisceApi({
          id: this.editForm.id,
        });
        if (code != 200) return;

        this.editForm = {};
        this.getdepositVoucherApiFn();
        this.$message({
          message: msg,
          type: "success",
        });
      } else {
        this.$message({
          message: "请点击删除信息",
          type: "warning",
        });
      }
    },

    // ------------------------自定义金额------------------------
    // 查询自定义金额
    async getConfigDepositSetting(){
      let result = await getConfigDepositSettingApi()
      if(result.code==200){
        // 问金有效期
        let expirationObj = result.data.find(item=>{
          return item.type == 'd_voucher_expiration'
        })
        // 每多少元增加赠送比例
        let limitObj = result.data.find(item=>{
          return item.type == 'd_voucher_limit'
        })
        // 赠送比例
        let scaleObj = result.data.find(item=>{
          return item.type == 'd_voucher_scale'
        })

        let custom = this.tableList.find(item=>{
          return item.amount == '自定义金额'
        })
        custom.expirationId = expirationObj.id //问金有效期id
        custom.expiration = expirationObj.value //问金有效期
        custom.limitId = limitObj.id //每多少元增加赠送比例id
        custom.limit = limitObj.value //每多少元增加赠送比例
        custom.scaleId = scaleObj.id //赠送比例Id
        custom.scale = scaleObj.value //赠送比例
      }
    },
    
    // 设置自定义问金保存
    async customSubmit(){
      await this.$refs.form["validate"]();
      let editForm = this.editForm;
      let data = []
      data.push({
        id: editForm.expirationId,
        value: editForm.expiration
      })
      data.push({
        id: editForm.limitId,
        value: editForm.limit
      })
      data.push({
        id: editForm.scaleId,
        value: editForm.scale
      })
      // 设置自定义问金参数
      this.editConfig(data)
    },

    // 设置自定义问金参数
    async editConfig(data){
      let result = await editConfigApi(data)
      if(result.code){
        this.getConfigDepositSetting()
        this.$message({message: "修改成功", type: "success"});
      }
    },

    resetForm() {
      this.$refs.form.resetFields();
    },

    // 当前页发生改变时
    handleCurrentChange(pageNum) {
      this.pageing.pageNum = pageNum;
      this.getdepositVoucherApiFn();
    },

    // 页容量发生改变
    handleSizeChange(pageSize) {
      this.pageing.pageSize = pageSize;
      this.getdepositVoucherApiFn();
    },
  },
};
</script>

<style scoped>
::v-deep .el-card__body {
  height: 100%;
}
::v-deep .el-card__body > div {
  height: 92%;
  overflow-y: auto;
}
::v-deep .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

.el-row .el-col > .el-card {
  position: relative;
}

.el-form {
  margin-bottom: 60px;
}
.wss-container .main-box {
  height: calc(100% - 60px);
}

.el-form >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before, 
.el-form >>> .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label:before{
  display: none;
}

/* 赠送比例 */
.customBox >>> .el-form-item__content{
  display: flex;
}
.customBox >>> .el-form-item__content p{
  margin: 0;
  font-size: 14px;
}
.customBox >>> .el-form-item__content .el-form-item{
  width: 80px;
  margin: 0 5px;
}

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 8px 30px !important;
}
::v-deep .subBtn > .el-button {
  width: 100px;
  padding: 8px 0;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn > .el-button.el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
</style>